package com.whisperly.echotalk.starryb.schemas;

import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.os.Bundle;
import android.os.Handler;
import android.os.LocaleList;
import android.os.Looper;
import android.preference.PreferenceManager;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;

import com.whisperly.echotalk.account.FindPassword;
import com.whisperly.echotalk.bllmodel.UserWithChat;
import com.whisperly.echotalk.starryb.R;
import com.whisperly.echotalk.starryb.utils.AppsManager;
import com.whisperly.echotalk.starryb.utils.DatabaseHelper;
import com.whisperly.echotalk.starryb.utils.EmailUtil;
import com.whisperly.echotalk.starryb.utils.GlobalData;
import com.whisperly.echotalk.starryb.utils.MD5Utils;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Locale;

import cn.bmob.v3.BmobQuery;
import cn.bmob.v3.datatype.BmobQueryResult;
import cn.bmob.v3.exception.BmobException;
import cn.bmob.v3.listener.FindListener;
import cn.bmob.v3.listener.SQLQueryListener;
import cn.bmob.v3.listener.UpdateListener;

public class Login extends AppCompatActivity {

    private EditText user_name;
    private EditText psw;
    private Button login;
    private TextView register;
    private TextView find_psw;

    private View loadingView;

    @Override
    protected void attachBaseContext(Context newBase) {
        SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(newBase);
        String languageCode = prefs.getString("language", "en");
        super.attachBaseContext(updateResources(newBase, languageCode));
    }

    public Context updateResources(Context context, String languageCode) {
        Locale locale = new Locale(languageCode);
        Locale.setDefault(locale);

        Resources res = context.getResources();
        Configuration config = new Configuration(res.getConfiguration());
        config.setLocale(locale);
        LocaleList localeList = new LocaleList(locale);
        LocaleList.setDefault(localeList);
        config.setLocales(localeList);
        context = context.createConfigurationContext(config);
        return context;
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.login);
        AppsManager.addActivity(this);
        user_name = findViewById(R.id.user_name);
        psw = findViewById(R.id.psw);
        login = findViewById(R.id.login);
        register = findViewById(R.id.register);
        find_psw = findViewById(R.id.find_psw);
        loadingView = getLayoutInflater().inflate(R.layout.layout_loading, null);

        login.setOnClickListener(v -> {
            showLoading();
            new Handler(Looper.getMainLooper()).postDelayed(()->{
                String name = user_name.getText().toString().trim();
                String password = psw.getText().toString().trim();

                if (name.length() == 0 || password.length() == 0) {
                    showLoginDialog(getString(R.string.The_account_number_or_password_cannot_be_empty), false);
                    hideLoading();
                    return;
                }

                password = MD5Utils.stringMD5(password);
                BmobQuery<UserWithChat> bmobQuery = new BmobQuery<>();
                bmobQuery.doSQLQuery("select * from UserWithChat where name = '" + name + "' and password = '" + password + "' ", new SQLQueryListener<UserWithChat>() {
                    @Override
                    public void done(BmobQueryResult<UserWithChat> bmobQueryResult, BmobException e) {
                        if (e == null){
                            List<UserWithChat> results = bmobQueryResult.getResults();
                            if (results.size()!=0){
                                for (UserWithChat user : results) {
                                    String currentTime = new SimpleDateFormat("yyyy-MM-dd", Locale.getDefault()).format(new Date());
                                    UserWithChat userWithChat = new UserWithChat();
                                    userWithChat.setLoginTime(currentTime);
                                    userWithChat.update(user.getObjectId(), new UpdateListener() {
                                        @Override
                                        public void done(BmobException e) {
                                            if (e != null) {
                                                Log.e("e", "更新登录时间错误");
                                            }
                                        }
                                    });
                                    @SuppressLint("DefaultLocale") String loginId = "Blink " + user.getObjectId();
                                    user.setLoginId(loginId);
                                    GlobalData.setUsername(name);
                                    GlobalData.setUser(user.getObjectId(), user);
                                    showLoginDialog(getString(R.string.Login_successful), true);
                                    return;
                                }

                            }else {
                                psw.setError(getString(R.string.The_account_number_or_password_is_incorrect));
                                showLoginDialog(getString(R.string.The_account_number_or_password_is_incorrect), false);
                            }

                        }else {
                            Toast.makeText(Login.this, R.string.Network_error, Toast.LENGTH_SHORT).show();
                        }
                        hideLoading();
                    }
                });
            },1000);
        });

        register.setOnClickListener(v -> {
            Intent intent = new Intent(this, Register.class);
            startActivity(intent);
//            overridePendingTransition(R.anim.slide_up, R.anim.slide_down);
            finish();
        });

        find_psw.setOnClickListener(v -> {
            Intent intent = new Intent(this, FindPassword.class);
            startActivity(intent);
        });
    }

    private void showLoading() {
        // Ensure loadingView doesn't have a parent before adding it
        if (loadingView.getParent() == null) {
            ((ViewGroup) findViewById(android.R.id.content)).addView(loadingView);
            Log.d("LoginActivity", "Loading view added");
        }
    }

    private void hideLoading() {
        ((ViewGroup) findViewById(android.R.id.content)).removeView(loadingView);
    }

    private void showLoginDialog(String message, boolean flag) {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle(R.string.Prompt);
        builder.setMessage(message);
        builder.setPositiveButton(R.string.OK, (dialog, which) -> {
            if (flag) {
                Intent intent = new Intent(this, AI.class);
                startActivity(intent);
//                overridePendingTransition(R.anim.fade_in, R.anim.fade_out);
                dialog.dismiss();
                finish();
                super.finish();
            }
            dialog.dismiss();
        });
        AlertDialog dialog = builder.create();
        dialog.setCancelable(false);
        dialog.show();
    }
}
